/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-28 13:39:23   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.OffsetDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.Shift;
import com.zx.cloud.common.token.PasswordHashUtil;
import com.zx.cloud.controller.StatusCode;
import com.zx.cloud.domain.Client;
import com.zx.cloud.domain.ClientAuth;
import com.zx.cloud.domain.ClientBankCard;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.VerifyMsg;
import com.zx.cloud.persistence.ClientAuthMapper;
import com.zx.cloud.persistence.ClientInfoMapper;
import com.zx.cloud.persistence.ClientMapper;
import com.zx.cloud.persistence.CrudMapper;

@Transactional
@Service
public class ClientService extends CrudServiceImpl<Client>{
    
    @Autowired
	private ClientAuthService clientAuthService;
    @Autowired
    private ClientInfoService clientInfoService;
    @Autowired
    private ClientInfoMapper clientInfoMapper;

    @Autowired
    private VerifyMsgService verifyMsgService;
    
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private ClientAuthMapper clientAuthMapper;
    
  	@Autowired
    public ClientService(CrudMapper<Client> mapper) {
        super(mapper);
    }

  	public long handleRegisterClient(Client client){
  		
  		String loginName = client.getLoginName();
  		if(StringUtils.isNotEmpty(loginName)){
  			if(null != clientMapper.findLoginNameExist(loginName)){
  				Shift.fatal(StatusCode.USER_EXISTS, "用户已经存在, 请尝试登录");
  			}
  		}
  		
  		String loginPwd = client.getLoginPwd();
  		if(StringUtils.isNotEmpty(loginPwd)){
  			try {
  				//给用户密码加密
				client.setLoginPwd(PasswordHashUtil.createHash(loginPwd));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
  		}
  		//保存
  		super.insert(client);
  		
  		Client resultEntity = clientMapper.findLoginNameExist(loginName);
  		
  		//创建会员认证信息表
  		ClientAuth clientAuth = new ClientAuth();
  		clientAuth.setClientId(resultEntity.getId());
  		
  		//保存入会员认证信息
  		clientAuthService.insert(clientAuth);
  		
  		//创建会员详细信息表
  		ClientInfo clientInfo = new ClientInfo();
  		clientInfo.setClientId(resultEntity.getId());
  		clientInfo.setPhone(loginName);
  		
  		//保存入会员详细信息
  		clientInfoService.insert(clientInfo);
  		
  		//创建会员银行卡信息表
  		ClientBankCard clientBankCard = new ClientBankCard();
  		clientBankCard.setClientId(resultEntity.getId());
  		
  		//保存入会员银行卡信息
//  		clientBankCardService.insert(clientBankCard);
  		
  		return resultEntity.getId();
  	}
  	
  	public long handleLoginClient(Client client){
  		
  		String insLoginPwd = null;
  		
  		Client insClient = null;
  		
  		String loginName = client.getLoginName();
  		if(StringUtils.isNotEmpty(loginName)){
  			insClient = clientMapper.findLoginNameExist(loginName);
  			if(null != insClient){
  				insLoginPwd = insClient.getLoginPwd();
  			}else{
  				Shift.fatal(StatusCode.USER_NOT_EXISTS, "用户不存在, 请先注册");
  			}
  		}
  		
  		String loginPwd = client.getLoginPwd();
  		if(StringUtils.isNotEmpty(loginPwd)){
  			try {
				if(!PasswordHashUtil.validatePassword(loginPwd, insLoginPwd)){
					Shift.fatal(StatusCode.INVALID_CREDENTIAL, "用户名或密码错误");
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
  		}
  		
  		return insClient.getId();
  	}
  	
  	public int handleForgotPassword(Client client){
  		
  		int resultInt = 0;
  		
  		Client insClient = clientMapper.findLoginNameExist(client.getLoginName());
		if(null != insClient){
			try {
				insClient.setLoginPwd(PasswordHashUtil.createHash(client.getLoginPwd()));
				super.update(insClient);
				resultInt = 1;
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			}
		}else{
			Shift.fatal(StatusCode.USER_NOT_EXISTS, "用户不存在, 请先注册");
		}
  		
  		return resultInt;
  	}
  	
  	public int handleModifyPassword(Client client){
  		
  		int resultInt = 0; //操作结果状态 1：修改成功
  		
  		Client insClient = clientMapper.get(client.getId());
		try {
			if (!PasswordHashUtil.validatePassword(client.getOldLoginPwd(), insClient.getLoginPwd())) {
				Shift.fatal(StatusCode.OLD_PASSWORD_ERROR, "原密码输入错误");
			} else {
				insClient.setLoginPwd(PasswordHashUtil.createHash(client.getLoginPwd()));
				super.update(insClient);
				resultInt = 1;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
  		
  		return resultInt;
  	}
  	
  	public ClientAuth SelectClientAuth(Client client){
  		
  		ClientAuth result = clientAuthMapper.findByClientID(client.getId());
  		
  		return result;
  		
  	}
  	
  	public int handleClientIDCardMsg(Long userId, VerifyMsg verifyMsg){
  		
  		verifyMsg.setCreateDate(OffsetDateTime.now());
  		verifyMsgService.insert(verifyMsg); //保存用户身份证扫描信息
  		
  		if(null != userId){
  			ClientInfo clientInfo = clientInfoMapper.findClientById(userId);
  	  		if(null != clientInfo){
  	  	  		clientInfo.setRealName(verifyMsg.getName());
  	  	  		clientInfo.setSex(verifyMsg.getSex());
  	  	  		clientInfo.setIdNo(verifyMsg.getIdnum());
  	  	  		clientInfo.setIdAddr(verifyMsg.getAddress());
  	  	  		clientInfo.setNational(verifyMsg.getNation());
  	  	  		clientInfo.setFrontImg(verifyMsg.getTheFrontOfIDCard());
  	  	  		clientInfo.setBackImg(verifyMsg.getTheReverseOfIDCard());
  	  	  		clientInfo.setUpdateTime(OffsetDateTime.now());
  	  	  		
  	  	  		int year = Integer.parseInt(verifyMsg.getYear());
  	  	  		int month = Integer.parseInt(verifyMsg.getMonth());
  	  	  		int day = Integer.parseInt(verifyMsg.getDay());
  	  	  		
  	  	  		OffsetDateTime nowDate = OffsetDateTime.now();
  	  	  		int insYear = nowDate.getYear();
  	  	  		int insMonth = nowDate.getMonthValue();
  	  	  		int insDay = nowDate.getDayOfMonth();
  	  	  		
  	  	  		int yearMinus = insYear - year;
  	  	  		int monthMinus = insMonth - month;
  	  	  		int dayMinus = insDay - day;
  	  	  		
  	  	  		int age = insYear - year;
  	  	  		if (yearMinus < 0) { 
  	  	            age = 0;  
  	  	        } else if (yearMinus == 0) { 
  	  	            if (monthMinus < 0) {
  	  	                age = 0;  
  	  	            } else if (monthMinus == 0) { 
  	  	                if (dayMinus < 0) {
  	  	                    age = 0;  
  	  	                } else if (dayMinus >= 0) {  
  	  	                    age = 1;  
  	  	                }  
  	  	            } else if (monthMinus > 0) {  
  	  	                age = 1;  
  	  	            }  
  	  	        } else if (yearMinus > 0) {  
  	  	            if (monthMinus < 0) {
  	  	            } else if (monthMinus == 0) { 
  	  	                if (dayMinus < 0) {  
  	  	                } else if (dayMinus >= 0) {  
  	  	                    age = age + 1;  
  	  	                }  
  	  	            } else if (monthMinus > 0) {  
  	  	                age = age + 1;  
  	  	            }  
  	  	        }
  	  	  		clientInfo.setAge(age);
  	  	  		
  	  	  		clientInfoService.update(clientInfo); //保存会员详细信息的身份认证
  	  		}
  	  		
  	  		ClientAuth clientAuth = clientAuthMapper.findByClientID(userId);
	  		clientAuth.setIdState(1);
	  		clientAuth.setIdTime(OffsetDateTime.now());
	  		
	  		//判断是否全部认证
	  		if(clientAuth.getContactState() == 1 && clientAuth.getBankCardState() == 1 && 
	  				clientAuth.getPrivateMsg() == 1 && (clientAuth.getJobState() == 1 || clientAuth.getSchoolState() == 1)){
	  			clientAuth.setFlag(1);
	  		}
	  		
	  		clientAuthService.update(clientAuth); //保存会员认证信息修改-身份信息验证
  		}
  		
  		return 0;
  	}

}
